//头文件 
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>  //write函数头文件
#include <sys/types.h>  //open函数头文件 
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h> //strlen头文件
#include "pwm_ctrl.h"


int fd1; //文件描述符
 int len1; //
 int ret1; //
 char pwm2_path1[100];

//pwm2通道0导入
int pwm2_export(char *argv){

    fd1 = open("/sys/class/pwm/pwmchip0/export",O_WRONLY);

    if(fd1 < 0){
        printf("open /sys/class/pwm/pwmchip0/export error\n");
        return -1; 
    }

    len1 = strlen(argv);
    ret1 = write(fd1,argv,len1); //写入0通道序号

    if(ret1 < 0){
        printf("write /sys/class/pwm/pwmchip0/export error\n");
        return -2;
    }
    close(fd1);
}

//pwm2通道0导出
int pwm2_unexport(char *argv){

    fd1 = open("/sys/class/pwm/pwmchip0/unexport",O_WRONLY);

    if(fd1 < 0){
        printf("open /sys/class/pwm/pwmchip0/unexport error\n");
        return -1; 
    }

    len1 = strlen(argv);
    ret1 = write(fd1,argv,len1); //写入0通道序号

    if(ret1 < 0){
        printf("write /sys/class/pwm/pwmchip0/unexport error\n");
        return -2;
    }
    close(fd1);
}

//往pwm2通道0里写入周期和占空比
int pwm2_ctrl(char *arg, char *val)
{
    char file_path[100];//存放路径

 sprintf(pwm2_path1,"/sys/class/pwm/pwmchip0/pwm%s","0");
    
    sprintf(file_path,"%s/%s",pwm2_path1,arg);//获取路径，涉及到参数的传递，这里gpiopath为138
   
    fd1 = open(file_path,O_WRONLY);

    if(fd1 < 0){
        printf("open file_path error\n");
        return -1;
    }
    len1 = strlen(val);
    ret1 = write(fd1,val,len1); //写入参数‘周期’、‘占空比’、‘使能’
    if(ret1 < 0){
        printf("write file_path error\n");
        return -2;
    }
    close(fd1);
}


